#!/usr/bin/python
import SocketServer,sys,re,time,thread,threading,os,socket,random
import struct
Mcache = []
Buffer = []
class csnode:
        def PadMsg(self,msg):
		self.msg =msg
                while len(self.msg) < 1024:
                        self.msg=self.msg+' '
                return self.msg

	def connect_bootstrap(self):
		global Mcache
		sBootStrap = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sBootStrap.connect(('127.0.0.1', 7187))
		sBootStrap.send("REGISTER\r\n")
		time.sleep(0.2)
		resp = sBootStrap.recv(1024)
		#print 'Resposta: ',resp.strip()
		if resp.strip()=='OK':
		        #print "REGISTER OK"
			sBootStrap.send("LIST\r\n")
			time.sleep(0.2)
		        data = sBootStrap.recv(1024)
			data = data.strip().split('\r\n')
			sBootStrap.send("EXIT\r\n")
			sBootStrap.close()
			#print len(data)
			Mcache =  data
			#Mcache = ['192.168.1.3','192.168.1.3']
			offLine = []
			count = 0
			for ip in Mcache:
				try:
					#print 'voce esta tentando conectar em '+ ip
					sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
					sNode.connect((ip, 50007))
					sNode.send('PLAY')
					#print sNode.recv(1024)
					while 1:
						#sys.stdout.write(sNode.recv(1024)[1])
						#tam = sNode.recv(1024)
						data = sNode.recv(1024)
						#print len(data.strip())
						count = count+1
						#print len(data)
						#if count == 5:
						#	break
						id,chunk = struct.unpack('24s1000s',data)
						if count == 100:
						    pass
						else:
						    sys.stdout.write(chunk)
						#sys.stdout.write(data[25:])
				except socket.error:
					offLine.append(ip)
                                	#print 'erro no socket'
			#print offLine
	       
node = csnode()
node.connect_bootstrap()
